const { ProvinceModel, CityModel, SceneryModel } = require('../../models/index')


// 获取省份和城市数据
const getRegionData = async (req, res) => {
  try {
    const regions = await ProvinceModel.findAll({
      include: [
        {
          model: CityModel,
          as: 'city'
        }
      ]
    })

    // 转换成前端需要的数据格式
    const regionsFormData = regions.map(item => {
      return {
        value: item.province_id,
        label: item.name,
        children: item.city.map(item2 => {
          return {
            value: item2.city_id,
            label: item2.name
          }
        })
      }
    })

    res.status(200).json({
      title: '省份和城市数据',
      data: regionsFormData
    })
  } catch (error) {
    res.status(500).json({
      error: error.message
    })
  }
}

// 提供目的地页面省份城市和景点数据
const getProvinceCitySceneryData = async (req, res) => {
  try {
    const data = await ProvinceModel.findAll({
      include: [
        {
          model: CityModel,
          as: 'city',
          attributes: ['city_id', 'name'],
          include: [
            {
              model: SceneryModel,
              as: 'scenery_city',
              attributes: ['images'],
              limit: 1
            }
          ]
        }
      ]
    })

    // 把数据转换为前端需要的格式
    const formData = data.map(item => {
      return {
        p_id: item.province_id,
        p_name: item.name,
        city: item.city.filter(item2 => item2.scenery_city && item2.scenery_city.length > 0).map(item3 => {
          return {
            c_id: item3.city_id,
            c_name: item3.name,
            image: item3.scenery_city[0].images[0]
          }
        })
      }
    })

    res.status(200).json({
      title: '省份和有景点的城市数据',
      data: formData
    })
  } catch (error) {
    res.status(500).json({
      error: error.message
    })
  }
}


module.exports = {
  getRegionData,
  getProvinceCitySceneryData
}

